# -*- coding = utf-8 -*-
# @Time    : 2025/4/9 上午10:43
# @Author  : yqk
# @File    : main.py
# @Software: PyCharm
# main.py
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
import time
import re
from CaptchaSolver import CaptchaSolver  # 引入CaptchaSolver类
# 初始化webdriver
service = Service(r'D:\python-code\chromedriver-win64\chromedriver.exe')

opt = Options()
opt.add_argument('--disable-blink-features=AutomationControlled')
opt.page_load_strategy = 'normal'

# 创建webdriver对象
driver = webdriver.Chrome(service=service, options=opt)
driver.get("https://www.douban.com/")
driver.maximize_window()

# 切换到登录页面
driver.switch_to.frame(0)

# 点击使用密码登录
pwd_login = driver.find_element(By.XPATH, '/html/body/div[1]/div[1]/ul[1]/li[2]')
pwd_login.click()
time.sleep(1)

# 输入账号密码
user_name = driver.find_element(By.XPATH, '//*[@id="username"]')
user_name.send_keys("850994281@qq.com")
password = driver.find_element(By.XPATH, '//*[@id="password"]')
password.send_keys("123")

# 点击登录
login = driver.find_element(By.XPATH, '/html/body/div[1]/div[2]/div[1]/div[5]/a')
login.click()
time.sleep(3)

# 进入滑块验证码iframe
driver.switch_to.frame('tcaptcha_iframe_dy')

# 找到缺口验证码图片位置
src = driver.find_element(By.XPATH, '//*[@id="slideBg"]')
style = src.get_attribute('style')

# 通过正则表达式提取url中的地址
compile_ = re.compile(r'background-image: url\("(.*?)"\)')
png_address = re.findall(compile_, style)
print(png_address)

# 使用CaptchaSolver类获取滑块位置
captcha_solver = CaptchaSolver(png_address[0])  # 创建CaptchaSolver对象
slider_pos = captcha_solver.get_slider_position()  # 获取滑块位置

# 获取滑动条元素
slide = driver.find_element(By.XPATH, '//*[@id="tcOperation"]/div[6]')

# 图片实际像素与浏览器中图片像素有差异，浏览器中图片像素大概是实际图片的41%, 由于像素缩小，减去30像素是为了平滑距离
result = int(slider_pos * 0.41) - 30

# 滑动滑块
ActionChains(driver).drag_and_drop_by_offset(slide, result, 0).perform()

time.sleep(5)

driver.quit()
